<template>
  <div style="height: calc(100% - 20px);" class="relate-table-css">
    <div class="my-define-dialog-title">
      {{dialogTitle}}
      <div class="my-define-dialog-title-btn">
        <i @click="cancel()" class="saas-iconfont saas-icon-caozuo-quanping-shousuo"></i>
      </div>
    </div>
    <div ref="myTopMenu" style="position: relative;top:0;left:0;" class="my-define-table-toolbar"
      v-if="!reqData.operation.hideToolBar">
      <el-menu :default-openeds="menuOpeneds" :default-active="activeMenuIndex" menu-trigger="click"
        class="my-tool-bar-menu" mode="horizontal" :collapse="false" text-color="#1f2329" @open="handleOpenMenu">
        <el-submenu popper-class="my-sub-menu" index="top-query">
          <template slot="title">
            <svg-icon icon-class="icon-query" />
            筛选
          </template>
          <div class="my-toolbar-title">设置筛选</div>
          <el-dropdown-item v-for="(item, index) in queryData" :key="index">
            当
            <el-select size="mini" @change="(val)=>handleChangeQueryColumn(val,item)" :popper-append-to-body="false"
              v-model="item.id" style="width: 100px;" placeholder="请选择">
              <el-option v-if="item2.visibile" v-for="item2 in columnFinalQueryData" :key="item2.id"
                :label="item2.label" :value="item2.id">
                <svg-icon icon-class="menu-common" />
                <span>{{ item2.label }}</span>
              </el-option>
            </el-select>
            <el-select size="mini" @change="(val)=>handleChangeQueryCondition(val,item)" :popper-append-to-body="false"
              v-model="item.condition" style="width: 100px;" placeholder="请选择">
              <el-option v-for="(item2,index2) in item.conditionData" :key="index2" :label="item2.label"
                :value="item2.id">
              </el-option>
            </el-select>
            <el-input size="mini" @change="(val)=>handleChangeQueryKeyword(val,item)"
              v-if="item.condition!='weikong'&&item.condition!='buweikong'" v-model="item.keyword" mini
              style="width: 100px;" placeholder="请输入内容"></el-input>
            <i @click="doRemoveQuery(index)" class="el-icon-delete" style="margin-left: 10px;"></i>
          </el-dropdown-item>
          <div class="add-search-btn" @click="doAddQuery()">
            <el-link class="define-plus-icon" icon="el-icon-plus">
              添加筛选条件
            </el-link>
          </div>
        </el-submenu>
        <el-submenu popper-class="my-sub-menu" index="top-search">
          <template slot="title">
            <svg-icon icon-class="icon-search" />
            搜索
          </template>
          <el-dropdown-item style="width: 260px;padding: 5px 10px 5px 10px;">
            <el-input prefix-icon="el-icon-search" @change="handleChangeSearch" size="mini"
              v-model="reqData.queryParams.queryText" placeholder="请输入关键字">
            </el-input>
          </el-dropdown-item>
        </el-submenu>
      </el-menu>
      <div style="position: unset;">
        <el-select size="mini" v-model="chosenStatus" placeholder="所有记录" @change="onChangeRecord">
          <el-option v-for="item in chosenOptions" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </div>
    </div>
    <div style="width: 96%; margin: 0 auto; margin-top: 0px;height: calc(100% - 50px)">
      <relate-table-basic ref="relateTableBasic" v-if="tableType==1" :reqData="reqData"
        :columnFinalData="columnFinalVisibleData" :sceneType="sceneType" :sceneId="sceneId"
        :defineSceneId="defineSceneId" :tableHeight="getTableHeight()" :rowStyle="rowStyle">
      </relate-table-basic>
    </div>
  </div>
</template>
<script>
  import {
    queryList,
    saveRelate
  } from '@/api/system/queryData'
  import {
    mapGetters
  } from 'vuex'
  import {
    getColumns
  } from '@/api/system/column'
  import draggable from "vuedraggable"
  import relateTableBasic from "@/views/master/RelateTableBasic";
  export default {
    name: 'relate-table-grid',
    components: {
      draggable,
      relateTableBasic,
    },
    props: {
      sceneType: {
        type: Number,
        default: 0
      },
      sceneId: {
        type: Number,
        default: 0
      },
      defineSceneId: {
        type: Number,
        default: 0
      },
      defineColumnId: {
        type: Number,
        default: 0
      },
      rowId: {
        type: Number,
        default: 0
      },
      defaultTableType: {
        type: Number,
        default: 1
      },
      defaultTableHeight: {
        type: Number,
        default: 0
      },
      dialogTitle: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        nextPageIndex: 1,
        currentTotalCount: 0,
        defaultPageSize: 10,
        reqData: {
          loading: true,
          // 返回结果集
          tableData: [],
          // 查询参数
          queryParams: {
            queryText: undefined,
            pageIndex: 1,
            pageSize: 10,
            orderBy: 'Id',
            sort: 'descending',
            queryData: '',
            sortData: '',
            groupData: '',
            sceneId: 0,
            defineSceneId: 0,
            sceneType: 0,
            focusId: 0,
            defineColumnId: 0,
            rowId: 0,
            chosenStatus: 0
          },
          // 合计条数
          total: 0,
          //操作权限
          operation: {},
          rightMenuData: [],
          noMore: false
        },
        menuOpeneds: [],
        activeMenuIndex: '',
        allColumnData: [],
        columnFinalData: [],
        columnFinalVisibleData: [],
        columnFinalQueryData: [],
        columnFinalSortData: [],
        queryData: [],
        sortData: [{
          id: null,
          condition: null
        }],
        heightData: [{
          id: 1,
          label: '默认',
          height: '33px'
        }, {
          id: 2,
          label: '中等',
          height: '55px'
        }, {
          id: 3,
          label: '高',
          height: '77px'
        }, {
          id: 4,
          label: '极高',
          height: '110px'
        }],
        defaultSelectionIds: [],
        selectionIds: [],
        selectionData: [],
        rowStyle: {
          height: '33px'
        },
        // 表格高度
        tableHeight: window.innerHeight - 30,
        tableType: 0, // 1=表格 2=分组 3=看板
        chosenOptions: [{
          value: 0,
          label: '所有记录'
        }, {
          value: 1,
          label: '已选记录'
        }, {
          value: 2,
          label: '未选记录'
        }],
        chosenStatus: 0,
      }
    },
    computed: {
      ...mapGetters(['routers', 'sidebar'])
    },
    watch: {},
    created() {
      var that = this;
      that.getColumnData()
      if (that.defaultTableHeight) {
        that.tableHeight = that.defaultTableHeight
      }
      const queryDataStr = localStorage.getItem('query_data_' + this.sceneId)
      if (queryDataStr) {
        this.queryData = JSON.parse(queryDataStr)
        var queryPostData = this.getQueryPostData()
        this.reqData.queryParams.queryData = JSON.stringify(queryPostData)
      }
      const sortDataStr = localStorage.getItem('sort_data_' + this.sceneId)
      if (sortDataStr) {
        this.sortData = JSON.parse(sortDataStr)
        var sortPostData = this.getSortPostData()
        this.reqData.queryParams.sortData = JSON.stringify(sortPostData)
      }
      this.reqData.queryParams.sceneType = this.sceneType
      this.reqData.queryParams.sceneId = this.sceneId
      this.reqData.queryParams.defineSceneId = this.defineSceneId
      this.reqData.queryParams.defineColumnId = this.defineColumnId
      this.reqData.queryParams.rowId = this.rowId
      setTimeout(() => {
        this.getData()
      }, 10)
      that.tableType = 0
      setTimeout(() => {
        that.tableType = that.defaultTableType
      }, 500)
    },
    methods: {
      addClickEvent() {
        document.addEventListener('mousedown', this.handleClickEvent, false)
      },
      removeClickEvent() {
        document.removeEventListener('mousedown', this.handleClickEvent, false)
      },
      handleClickEvent(e) {
        let isIn = false
        let colDropMenus = document.querySelectorAll('.el-popper')
        colDropMenus.forEach((colDropMenu) => {
          if (colDropMenu.contains(e.target)) {
            isIn = true
            return false
          }
        })
        if (this.menuOpeneds.length > 0) {
          if (!this.$refs.myTopMenu.contains(e.target)) {
            if (!isIn) {
              let subMenus = document.querySelectorAll('.el-menu--horizontal.my-sub-menu')
              subMenus.forEach((sunMenu) => {
                if (sunMenu.contains(e.target)) {
                  isIn = true
                  return false
                }
              })
            }

            if (!isIn) {
              this.doCloseMenu()
              this.removeClickEvent()
            }
          }
        }
      },
      getData() {
        var that = this
        this.reqData.loading = true
        queryList(this.reqData.queryParams).then(res => {
          this.reqData.loading = false
          if (res.status) {
            if (this.reqData.queryParams.pageIndex == 1) {
              this.reqData.tableData = res.outputData.DataSource
            } else {
              this.reqData.tableData = this.reqData.tableData.concat(res.outputData.DataSource)
            }
            this.reqData.total = res.outputData.TotalCount
            this.reqData.noMore = this.reqData.tableData.length == this.reqData.total || this.reqData.total == 0
            this.currentTotalCount = this.reqData.tableData.length
            this.selectionIds = []
            this.selectionData = []
            this.defaultSelectionIds = res.outputData.selectIdList
            this.reqData.tableData.forEach((row) => {
              if (this.defaultSelectionIds.indexOf(row.Id) > -1) {
                this.selectionData.push(row)
              }
            })
            this.setDefaultSelect()
          }
        })
      },
      setDefaultSelect() {
        if (!this.$refs.relateTableBasic || !this.$refs.relateTableBasic.setTableRowsSelect) {
          setTimeout(() => {
            this.setDefaultSelect()
          }, 100)
          return
        }
        this.$refs.relateTableBasic.setTableRowsSelect(this.selectionData, true)
      },
      doSearch(option) {
        if (option) {
          if (option.queryText) {
            this.reqData.queryParams.queryText = option.queryText;
          }
          if (option.queryData) {
            this.reqData.queryParams.queryData = JSON.stringify(option.queryData);
          }
          if (option.sortData) {
            this.reqData.queryParams.sortData = JSON.stringify(option.sortData);
          }
          if (option.focusId) {
            this.reqData.queryParams.focusId = option.focusId
          }
          if (option.groupData) {
            this.reqData.queryParams.groupData = JSON.stringify(option.groupData);
          }
          if (option.goNext) {
            this.nextPageIndex++
          } else {
            this.nextPageIndex = 1
          }
        } else {
          this.nextPageIndex = 1
        }
        this.reqData.queryParams.pageIndex = this.nextPageIndex
        this.reqData.queryParams.pageSize = this.defaultPageSize
        this.getData()
      },
      onChangeRecord() {
        this.reqData.queryParams.chosenStatus = this.chosenStatus
        this.doSearch()
      },
      // 获取列
      getColumnData() {
        if (this.sceneType) {
          getColumns({
            sceneType: this.sceneType,
            sceneId: this.sceneId,
            defineSceneId: this.defineSceneId
          }).then(res => {
            if (res.status) {
              this.allColumnData = res.outputData.columnList
              this.columnFinalData = this.allColumnData.filter(function(item) {
                return !item.deleted;
              })
              this.setColumnData()
            }
          })
        } else {
          this.columnFinalData = this.columnData
          this.setColumnData()
        }
      },
      setColumnData() {
        this.columnFinalVisibleData = this.columnFinalData.filter(function(item) {
          return item.visibile;
        })
        this.columnFinalQueryData = this.columnFinalData.filter(function(item) {
          return item.canQuery && !item.deleted;
        })
        this.columnFinalSortData = this.columnFinalData.filter(function(item) {
          return item.canSort && !item.deleted;
        })
      },
      setSelectionIds(selectionIds, selectionData) {
        this.selectionIds = selectionIds
        this.selectionData = selectionData
      },
      // 添加筛选条件
      doAddQuery() {
        var that = this;
        that.queryData.push({
          id: null,
          columnId: null,
          defineId: null,
          condition: null,
          keyword: '',
          conditionData: []
        })
      },
      // 删除筛选条件
      doRemoveQuery(index) {
        this.queryData.splice(index, 1)
        this.handleStartQuery(true)
      },
      // 筛选条件选择列事件触发
      handleChangeQueryColumn(val, item) {
        var columnItem = null;
        this.columnFinalData.forEach(function(myItem) {
          if (myItem.id == val) {
            columnItem = myItem;
            return false
          }
        })
        item.columnId = columnItem.columnId
        item.defineId = columnItem.defineId
        item.conditionData = [];
        // 字符串
        if (columnItem.fieldType == '1') {
          item.conditionData.push({
            id: 'dengyu',
            label: '等于'
          })
          item.conditionData.push({
            id: 'budengyu',
            label: '不等于'
          })
          item.conditionData.push({
            id: 'baohan',
            label: '包含'
          })
          item.conditionData.push({
            id: 'bubaohan',
            label: '不包含'
          })
        } else {
          item.conditionData.push({
            id: 'dengyu',
            label: '='
          })
          item.conditionData.push({
            id: 'budengyu',
            label: '≠'
          })
          item.conditionData.push({
            id: 'dayu',
            label: '>'
          })
          item.conditionData.push({
            id: 'dayudengyu',
            label: '≥'
          })
          item.conditionData.push({
            id: 'xiaoyu',
            label: '<'
          })
          item.conditionData.push({
            id: 'xiaoyudengyu',
            label: '≤'
          })
        }
        item.conditionData.push({
          id: 'weikong',
          label: '为空'
        })
        item.conditionData.push({
          id: 'buweikong',
          label: '不为空'
        })
        this.handleStartQuery(false)
      },
      // 筛选条件选择列事件触发
      handleChangeQueryCondition(val, item) {
        this.handleStartQuery(false)
      },
      // 筛选条件选择列事件触发
      handleChangeQueryKeyword(val, item) {
        this.handleStartQuery(false)
      },
      // 执行查询
      handleStartQuery(forceLoad) {
        var postData = this.getQueryPostData()
        localStorage.setItem('query_data_' + this.sceneId, JSON.stringify(this.queryData))
        if (postData.length > 0 || forceLoad) {
          this.doSearch({
            queryData: postData
          })
        }
      },
      getQueryPostData() {
        var postData = [];
        this.queryData.forEach(function(item) {
          if (item.condition != 'weikong' && item.condition != 'buweikong') {
            if (item.id && item.condition && item.keyword) {
              postData.push({
                id: item.id,
                columnId: item.columnId,
                defineId: item.defineId,
                condition: item.condition,
                keyword: item.keyword
              })
            }
          } else {
            if (item.id && item.condition) {
              postData.push({
                id: item.id,
                columnId: item.columnId,
                defineId: item.defineId,
                condition: item.condition,
                keyword: ''
              })
            }
          }
        })
        return postData
      },
      getSortPostData() {
        var postData = [];
        this.sortData.forEach(function(item) {
          if (item.id && item.condition) {
            postData.push({
              id: item.id,
              columnId: item.columnId,
              defineId: item.defineId,
              condition: item.condition,
            })
          }
        })
        return postData
      },
      // 行高触发事件
      handleHeightCommand(command) {
        this.rowStyle.height = command.height;
      },
      // 触发搜索
      handleChangeSearch(val) {
        this.doSearch({
          queryText: val
        })
      },
      // 打开操作栏事件
      handleOpenMenu(key, keyPath) {
        this.menuOpeneds = []
        if (key.indexOf('top') > -1) {
          this.menuOpeneds.push(key)
        } else if (key.indexOf('sub-more') > -1) {
          this.menuOpeneds.push('top-more')
          this.menuOpeneds.push(key)
        }
        this.addClickEvent()
      },
      // 关闭操作栏方法
      doCloseMenu() {
        this.menuOpeneds = []
      },
      getTableHeight() {
        var winHeight = window.innerHeight - 180
        if (this.tableType == 1) {
          if (this.reqData.tableData.length == 0) {
            // return '200px'
          }
          var rowHeight = this.rowStyle.height.replace('px', '')
          var tableHeight = this.reqData.tableData.length * Number(rowHeight) + 40
          if (winHeight > tableHeight) {
            // return (tableHeight + 8) + 'px'
            // return 'auto'
          }
          // return '100%'
        }
        return '200px'
        // return (winHeight - 40) + 'px'
      },
      cancel() {
        this.$$parent(this, "closeRelatePop")
      },
      submitRelate() {
        var that = this;
        let canSave = false
        if (this.chosenStatus == 2) {
          if (this.defaultSelectionIds.length > 0) {
            this.reqData.tableData.forEach((row) => {
              if (this.defaultSelectionIds.indexOf(row.Id) > -1) {
                this.selectionData.push(row)
              }
            })
          }
        }
        if (this.selectionData.length != this.defaultSelectionIds.length) {
          canSave = true
        } else {
          this.selectionData.forEach((row) => {
            if (this.defaultSelectionIds.indexOf(row.Id) == -1) {
              canSave = true
              return false
            }
          })
        }
        if (!canSave) {
          this.cancel()
          return
        }
        var postData = []
        if (this.selectionData.length > 0) {
          var postData = []
          let fixedColumn = this.columnFinalData.find((x) => {
            return x.isFixed
          })
          let showColumn = this.columnFinalData.find((x) => {
            return x.visibile
          })
          this.selectionData.forEach((row) => {
            let relateId = row.Id
            let relateValue = ''
            if (fixedColumn && row[fixedColumn.name]) {
              relateValue = row[fixedColumn.name]
            } else if (showColumn && row[showColumn.name]) {
              relateValue = row[showColumn.name]
            }
            postData.push({
              relateId: relateId,
              relateValue: relateValue
            })
          })
        }
        saveRelate({
          relateSceneId: this.defineSceneId,
          defineColumnId: this.defineColumnId,
          rowId: this.rowId,
          postData: JSON.stringify(postData)
        }).then(res => {
          this.$$parent(this, "doSearch", {})
          this.cancel()
        })
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .relate-table-css {
    .my-toolbar-title {
      padding-left: 10px;
      font-size: 14px;
      margin: 5px 0;
    }

    .add-search-btn {
      margin: 15px 0 15px 10px;
      display: inline-block;
    }

    .my-tool-bar-menu.el-menu--collapse.el-menu {
      width: 100%;
      border-right: 0px;
    }

    .my-tool-bar-menu.el-menu--collapse .el-menu .el-menu-item {
      padding: 0 !important;
      line-height: 40px;
      height: 40px;
      font-size: 14px;
    }

    .my-tool-bar-menu.el-menu--collapse.el-menu .el-submenu__title {
      padding: 0 0 0 5px !important;
    }

    .el-menu--vertical .el-menu-item {
      line-height: 40px;
      height: 40px;
      font-size: 14px;
    }

    .el-menu--horizontal>.el-submenu .el-submenu__icon-arrow {
      margin-left: 0;
    }

    .el-menu.el-menu--popup {
      padding-left: 10px;
    }

    .my-mask-bg {
      background: rgba(0, 0, 0, 0);
      z-index: 1999;
      position: absolute;
      top: 0px;
      bottom: 0;
      width: 100%;
    }

    .my-define-focus-title {
      z-index: 2000;
      position: relative;
    }

    .my-mask-focus-bg {
      top: 0px;
    }

    .el-select {
      top: 5px;
    }

    .my-define-dropdown-menu0 .el-select-dropdown__item {
      padding-left: 5px;
    }

    .el-menu--horizontal.my-sub-menu-zd {
      border: solid 0.5px #dee0e3;
      background: #fff;
      border-radius: 6px;
    }

    .el-menu--horizontal.my-sub-menu {
      border: solid 0.5px #dee0e3;
      background: #fff;
      border-radius: 6px;
    }

    .el-menu--horizontal.my-sub-menu-2 {
      border: solid 0.5px #dee0e3;
      background: #fff;
      border-radius: 6px;
    }

    .el-menu {
      .svg-icon {
        width: 15px;
        height: 13px;
        vertical-align: -1px;
        fill: #757575;
      }

      .icon-edit.svg-icon {
        width: 10px;
        height: 10px;
        margin-left: 5px;
        vertical-align: 1px;
      }
    }

    .my-tableview-menu.el-submenu {
      margin-right: 20px;
    }

    .my-tableview-menu.el-submenu .svg-icon {
      vertical-align: -2px;
    }

    .el-dropdown-menu__item.focus-item {
      padding: 0 10px;
    }

    .define-plus-icon.el-link {
      font-size: 15px;
    }

    .column-dropdown-menu {
      .svg-icon {
        width: 14px;
        height: 14px;
      }

      .el-dropdown-menu__item {
        padding: 0px;
      }

      .el-dropdown-menu__item.column-dropdown-item-edit {
        padding: 0 15px 0 10px;
      }

      .column-dropdown-remove-div {
        padding: 0 15px 0 10px;
      }
    }

    .my-toolbar-desc {
      font-size: 12px;
      color: #888;
      padding: 10px;
    }

    .my-color-picker.el-color-picker--mini {
      vertical-align: -2px;
    }

    .checkbox-style .el-form-item.el-form-item--mini {
      margin-bottom: 0px;
    }

    .my-color-picker.el-color-picker--mini .el-color-picker__trigger {
      width: 18px;
      height: 18px;
      padding: 0px;
    }

    .el-form-item--mini .el-form-item__label {
      padding: 0px;
    }
  }
</style>
